package com.yunche.yunchebusiness.ui.activity.main

import android.content.Intent
import android.os.Bundle
import com.yunche.yunchebusiness.R
import com.yunche.yunchebusiness.api.Api
import com.yunche.yunchebusiness.base.BaseActivity
import com.yunche.yunchebusiness.common.CommonDialog
import com.yunche.yunchebusiness.common.Constant
import com.yunche.yunchebusiness.entity.LoginEntity
import com.yunche.yunchebusiness.mvp.contract.LoginContract
import com.yunche.yunchebusiness.mvp.presenter.LoginPresenter
import com.yunche.yunchebusiness.ui.activity.MainActivity
import com.yunche.yunchebusiness.ui.activity.system.ChangeGestureActivity
import com.yunche.yunchebusiness.utils.SpHelper
import com.yunche.yunchebusiness.utils.ToastyUtils

class SplashActivity : BaseActivity(), LoginContract.View {
    override fun showError(msg: String) {
        ToastyUtils.showError(msg)
        openActivity(LoginActivity::class.java)
        finish()
    }

    private val mPresenter by lazy {
        LoginPresenter()
    }

    override fun loginSuccess(loginEntity: LoginEntity) {
        SpHelper.putValue(Constant.SP_KEY.TOKEN, loginEntity.token)
        SpHelper.putValue(Constant.SP_KEY.TENANT_ID, loginEntity.id)

        if (loginEntity.checkTenant) {
            openActivity(MainActivity::class.java)
            finish()
        } else {
            openActivity(AppendTenantInfoActivity::class.java)
            finish()
        }
    }

    override fun showLoading() {
        CommonDialog.showLoading(mContext!!, Constant.Logging)
    }

    override fun hideLoading() {
        CommonDialog.cancle()
    }

    override fun setLayout(): Int = R.layout.activity_splash

    override fun initView() {
        mPresenter.attachView(this)
    }

    override fun initData() {
        if (Api.isSetGesture()) {
            var bundle = Bundle()
            bundle.putBoolean("isLogin", false)
            openActivityForResult(ChangeGestureActivity::class.java, bundle, 1001)
        } else {
            openActivity(LoginActivity::class.java)
            finish()
        }
    }

    override fun initEvent() {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            Constant.RESULT_GESTURE_SUCCESS -> mPresenter.login(Api.getUserName(), Api.getPassword())
            Constant.RESULT_GESTURE_ERROR,
            Constant.RESULT_FORGET -> {
                SpHelper.clearPreference(Constant.SP_KEY.IS_SET_GESTURE)
                SpHelper.clearPreference(Constant.SP_KEY.PASSWORD)
                openActivity(LoginActivity::class.java)
                finish()
            }
            Constant.FINISH -> {
                finish()
            }
        }
    }


}
